package cn.chiship.framework.business.core.config;

import cn.chiship.framework.common.config.VisiableThreadPoolTaskExecutorConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置类
 * @author lijian
 */
@Configuration
public class ThreadPoolExecutorConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(ThreadPoolExecutorConfig.class);
    /**
     * 获得Java虚拟机可用的处理器个数 + 1
     */
    private static final int THREADS = Runtime.getRuntime().availableProcessors() + 1;

    private int corePoolSize = THREADS;
    private int maxPoolSize = 2*THREADS;
    private int queueCapacity = 1024;
    private String namePrefix = "async-service-";

    /**
     * 异步线程池
     * @return Executor   执行器
     */
    @Bean("asyncServiceExecutor")
    public Executor asyncServiceExecutor() {
        LOGGER.info("start asyncServiceExecutor");
        ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutorConfig();
        //配置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //配置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(namePrefix);

        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }
}
